package com.ruoyi.video.service.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.video.domain.VideoGroup;
import com.ruoyi.video.domain.VideoStream;
import com.ruoyi.video.domain.VideoTree;
import com.ruoyi.video.mapper.VideoGroupMapper;
import com.ruoyi.video.server.push.PushData;
import com.ruoyi.video.server.push.PushMessage;
import com.ruoyi.video.task.ServerApplicationRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.video.mapper.VideoCameraMapper;
import com.ruoyi.video.domain.VideoCamera;
import com.ruoyi.video.service.IVideoCameraService;

import javax.validation.Validator;

/**
 * 摄像机Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-09
 */
@Service
public class VideoCameraServiceImpl implements IVideoCameraService 
{
    @Autowired
    private VideoCameraMapper videoCameraMapper;
    @Autowired
    private VideoGroupMapper videoGroupMapper;

    @Autowired
    protected Validator validator;


    /**
     * 查询摄像机列表
     *
     * @param videoCamera 摄像机
     * @return 摄像机集合
     */
    public List<VideoTree> buildingTree(VideoCamera videoCamera){
        List<VideoGroup> groupList = videoGroupMapper.selectVideoGroupList(new VideoGroup());
        groupList.sort(Comparator.comparingInt(VideoGroup::getSorts));

        List<VideoCamera> cameraList = videoCameraMapper.selectVideoCameraList(videoCamera);
        List<VideoTree> tree = new ArrayList<>();
        List<VideoCamera> nl = new ArrayList<>();
        //按分组生成
        for(VideoGroup group:groupList){
            VideoTree node = VideoTree.groupTree(group.getName(), group.getId());
            for(VideoCamera camera:cameraList){
                if(StringUtils.isEmpty(camera.getGroupName())){
                    nl.add(camera);
                }else if(group.getName().equalsIgnoreCase(camera.getGroupName())){
                    node.addCamera(camera);
                }
            }
            tree.add(node);
        }
        //未分组
        if(StringUtils.isNotEmpty(nl)){
            VideoTree node = VideoTree.groupTree("未分组", 0L);
            for(VideoCamera camera:nl){
                node.addCamera(camera);
            }
            tree.add(node);
        }
        return tree;
    }

    /**
     * 查询摄像机的流
     *
     * @param id 摄像机主键
     * @return 摄像机
     */
    @Override
    public VideoStream getVideoCameraStream(Long id){
        VideoCamera videoCamera = selectVideoCameraById(id);
        if(videoCamera == null){
            return null;
        }

        return ServerApplicationRunner.getHandler(videoCamera.getType()).getStream(videoCamera);
    }

    /**
     * 摄像机截图
     *
     * @param id 摄像机主键
     * @return 摄像机
     */
    @Override
    public String snapVideoCamera(Long id){

        VideoCamera videoCamera = selectVideoCameraById(id);
        if(videoCamera == null){
            return null;
        }

        return ServerApplicationRunner.getHandler(videoCamera.getType()).snap(videoCamera);
    }

    /**
     * 查询摄像机
     *
     * @param ip 摄像机IP
     * @param type 摄像机接入方式
     * @return 摄像机
     */
    @Override
    public VideoCamera selectVideoCameraByIp(String ip,String type){
        return videoCameraMapper.selectVideoCameraByIp(ip, type);
    }

    /**
     * 查询摄像机
     *
     * @param code 摄像机代码
     * @return 摄像机
     */
    @Override
    public VideoCamera selectVideoCameraByCode(String code){
        return videoCameraMapper.selectVideoCameraByCode(code);
    }

    /**
     * 查询摄像机
     * 
     * @param id 摄像机主键
     * @return 摄像机
     */
    @Override
    public VideoCamera selectVideoCameraById(Long id)
    {
        return videoCameraMapper.selectVideoCameraById(id);
    }

    /**
     * 查询摄像机列表
     * 
     * @param videoCamera 摄像机
     * @return 摄像机
     */
    @Override
    public List<VideoCamera> selectVideoCameraList(VideoCamera videoCamera)
    {
        return videoCameraMapper.selectVideoCameraList(videoCamera);
    }

    /**
     * 新增摄像机
     * 
     * @param videoCamera 摄像机
     * @return 结果
     */
    @Override
    @PushData(name = "video_camera", action = PushData.ACTION_ADD)
    public int insertVideoCamera(VideoCamera videoCamera)
    {
        VideoCamera old = videoCameraMapper.selectVideoCameraByCode(videoCamera.getCode());
        if(old != null){
            throw new ServiceException("摄像机代码不能重复:"+ videoCamera.getCode());
        }
        if(videoCamera.getOnline() == null){
            videoCamera.setOnline("Y");
        }
        videoCamera.setCreateTime(new Date());
        return videoCameraMapper.insertVideoCamera(videoCamera);
    }

    /**
     * 修改摄像机
     * 
     * @param videoCamera 摄像机
     * @return 结果
     */
    @Override
    //@PushData(name = "video_camera", action = PushData.ACTION_UPDATE)
    public int updateVideoCamera(VideoCamera videoCamera)
    {
        videoCamera.setUpdateTime(new Date());
        return videoCameraMapper.updateVideoCamera(videoCamera);
    }

    /**
     * 批量删除摄像机
     * 
     * @param ids 需要删除的摄像机主键
     * @return 结果
     */
    @Override
    @PushData(name = "video_camera", action = PushData.ACTION_DELETE)
    public int deleteVideoCameraByIds(Long[] ids)
    {
        return videoCameraMapper.deleteVideoCameraByIds(ids);
    }

    /**
     * 删除摄像机信息
     * 
     * @param id 摄像机主键
     * @return 结果
     */
    @Override
    @PushData(name = "video_camera", action = PushData.ACTION_DELETE)
    public int deleteVideoCameraById(Long id)
    {
        return videoCameraMapper.deleteVideoCameraById(id);
    }


    /**
     * 导入数据
     *
     * @param dataList 数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importData(List<VideoCamera> dataList, Boolean isUpdateSupport, String operName){
        if (StringUtils.isNull(dataList) || dataList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (VideoCamera videoCamera : dataList)
        {
            try
            {
                BeanValidators.validateWithException(validator, videoCamera);
                if(StringUtils.isEmpty(videoCamera.getStatus())){
                    videoCamera.setStatus("1");
                }
                // 验证是否存在
                VideoCamera old = videoCameraMapper.selectVideoCameraByCode(videoCamera.getCode());
                if (old == null)
                {
                    videoCamera.setOnline("Y");
                    videoCamera.setCreateBy(operName);
                    videoCamera.setCreateTime(new Date());
                    insertVideoCamera(videoCamera);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、摄像机 " + videoCamera.getCode() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    videoCamera.setUpdateBy(operName);
                    videoCamera.setUpdateTime(new Date());
                    updateVideoCamera(videoCamera);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、摄像机 " + videoCamera.getCode() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、摄像机 " + videoCamera.getCode() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、摄像机 " + videoCamera.getCode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
